/******************************************************************************
 * Copyright (C) 2016  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "node/util/option_set.h"

namespace node {
    namespace util {

    option_set::option_set(void)
        : _options()
    {

    }
    option_set::~option_set(void)
    {

    }

    void option_set::add_option(const node::util::option &option)
    {
        for (const_iterator iter = _options.begin(), iter_end = _options.end();
                iter != iter_end; ++iter)
        {
            if (option.get_name() == iter->get_name())
            {
                return;
            }
        }
        _options.push_back(option);
    }
    void option_set::process(std::vector<std::string> &arguments)
    {
        typedef std::vector<std::string>::iterator stringvector_iter;
        for (stringvector_iter arg_iter = arguments.begin();
             arg_iter != arguments.end();)
        {
            bool unknown_arg = true;
            for (iterator opt_iter = _options.begin(), opt_end = _options.end();
                    opt_iter != opt_end; ++opt_iter)
            {
                if (opt_iter->match_name(*arg_iter) || opt_iter->match_short_name(*arg_iter))
                {
                    arg_iter = arguments.erase(arg_iter);
                    if (opt_iter->has_argument() && arg_iter != arguments.end())
                    {
                        opt_iter->set_value(*arg_iter);
                        opt_iter->set_is_valid(true);
                        arg_iter = arguments.erase(arg_iter);
                    } else if (!opt_iter->has_argument())
                    {
                        opt_iter->set_is_valid(true);
                    }
                    unknown_arg = false;
                    break;
                }
            }
            if (unknown_arg) ++arg_iter;
        }
    }

}}
